package com.wsz.security.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsz.security.pojo.Role;
import com.wsz.security.pojo.User;
import com.wsz.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyUserDetailService implements UserDetailsService {
    private final UserService userService;

    @Autowired
    public MyUserDetailService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println(s);

        User user = userService.getOne(new QueryWrapper<User>().eq("username", s));

        if(user == null){
            throw new UsernameNotFoundException("用户名不正确");
        }else{
            List<Role> roles  = userService.getRolesByUid(user.getId());
            user.setRoles(roles);
        }

        return user;
    }
}
